#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "pluginmanager.h"
#include <qdebug.h>
#include <functional>
#include <QFileDialog>
#include <qmessagebox.h>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    init_plugins();
    // 设置分裂器比例 setStretchFactor方法的参数分别是子控件索引、拉伸参数
    ui->splitter->setStretchFactor(0,5);
    ui->splitter->setStretchFactor(1,5);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::mainCallBack(const QString & info)
{
    add_plugin_info(info);
}



void MainWindow::init_plugins()
{
    ui->tbw_main->clear();

    connect(&PluginManager::instance(),&PluginManager::sigAddPlugin,this,[&](QString name){
        add_plugin_info("add " + name);
        add_plugin_tab(name);
    });

    connect(&PluginManager::instance(),&PluginManager::sigDelPlugin,this,[&](QString name){
        add_plugin_info("del " + name);
        del_plugin_tab(name);
    });
}


/*
    加载当前插件
*/
void MainWindow::on_pb_load_plugin_clicked()
{

    QString pluginPath = ui->cb_plugin_list->currentData().toString();
    if(!PluginManager::instance().loadPlugin(pluginPath))
    {
        QMessageBox::warning(this,"tip","load failed!!");
        return;
    }


}


/**
 * 打开插件目录,获取插件名称 和 路径 */

void MainWindow::on_pb_open_floder_clicked()
{
    QString dirPath = QFileDialog::getExistingDirectory(this, "选择插件目录", "");
    if (dirPath.isEmpty()) {
        return;
    }

    QDir pluginDir(dirPath);
    QStringList filters;
#ifdef Q_OS_WIN
    filters << "*.dll";
#else
    filters << "*.so";
#endif
    QFileInfoList fileList = pluginDir.entryInfoList(filters, QDir::Files);

    for (const QFileInfo &fileInfo : fileList) {
        QString pluginName = fileInfo.fileName();
        QString pluginPath = fileInfo.absoluteFilePath();
        qDebug() << "插件名称:" << pluginName << "路径:" << pluginPath;
        // 你可以在这里将插件信息显示到界面上
        ui->cb_plugin_list->addItem(pluginName,pluginPath);
    }
}


/*
    添加一行日志到te_plugin_info 中，格式 [时间] info
*/
void MainWindow::add_plugin_info(QString info)
{
    ui->te_plugin_info->append(QDateTime::currentDateTime().toString("[hh:mm:ss] ") + info);
}


/*
    添加一个插件tab
*/
void MainWindow::add_plugin_tab(QString name)
{
    auto* plugin = PluginManager::instance().getPlugin(name);
    if(!plugin)
    {
        QMessageBox::warning(this,"错误","插件不存在");
        return;
    }

    mainwindowCallBack callback = std::bind(&MainWindow::mainCallBack,this,std::placeholders::_1);
    plugin->initialize(callback);

    ui->tbw_main->addTab(plugin->createUI(),plugin->name());
}


/*
    删除一个插件tab
*/
void MainWindow::del_plugin_tab(QString name)
{
    for (int i = 0; i < ui->tbw_main->count(); ++i) {
        if (ui->tbw_main->tabText(i) == name) {
            QWidget* tab = ui->tbw_main->widget(i);
            ui->tbw_main->removeTab(i);
            tab->deleteLater(); // 释放 tab 占用的资源
            break;
        }
    }
}
